import { Component } from 'react';
import { Button, Icon,InputGroup,Tree,Tooltip,Divider,Tabs,Tab,Popover,Menu,MenuItem, Spinner } from '@blueprintjs/core';
import { ajax_post,ajax_get } from '../../../api/ajax';
import { trim } from '../../../utils/util';
import Blank from '../../../components/Blank';
import ScrollWrapper from '../../../components/ScrollWrapper';
import styles from './NameList.less';
import { updateState } from '../../../models/global';
import { connect } from 'dva';
import * as turf from '@turf/turf';
import {ToasterWarning} from '../../../components/Toaster';
import {flashLayer} from '../../../utils/animate';

/**
 * 基础地名列表
 */
class NameList extends Component {
    constructor(props) {
        super(props);
		this.state = {
			// tab: "roads", // 当前面板
			road: null,
			nodes: [],
			filterKey: '',
			loaded: false,
		}
    }

	handleNavbarTabChange = (val) => {
		// this.setState({tab: val})
		if(val === "back") {
			this.props.handleTabChange("list");
			updateState({namelistTab:"roads"})
			// this.setState({tab: "road", nodes: [], road: null});
			this.setState({nodes: [], road: null});
		} else {
			updateState({namelistTab:val})
			this.setState({nodes: [], road: null});
			this.queryRoad(val);
		}
	}

	refNodes = (ref) => {
		this.road_child = ref;
	}

	/**
	 * 从地图中移除定位结果
	 */
	removeLocate = () => {
		const {map,sign} = this.props;
		if(map) {
			clearInterval(sign);
			cancelAnimationFrame(sign);
			const {marker} = this.state;
			if(marker) marker.remove();
			const layerId = 'dmdz-locate-layer';
			const layer = map.getLayer(layerId);
			if(layer) {
				map.removeLayer(layerId);
			}
			const layer1 = map.getLayer('searchLayer1');
			if(layer1) {
			    map.removeLayer('searchLayer1');
			}
			const layer2 = map.getLayer('searchLayer2');
			if(layer2) {
			    map.removeLayer('searchLayer2');
			}
			const layer4 = map.getLayer('atlasdata-ext-dmdz-roads-source-layer');
			if(layer4) {
				map.removeLayer('atlasdata-ext-dmdz-roads-source-layer')
			}
			const layer5 = map.getLayer('atlasdata-ext-dmdz-focus-poi-source');
			if(layer5) {
				map.removeLayer('atlasdata-ext-dmdz-focus-poi-source')
			}
			const layer6 = map.getLayer('dmdz-locate-layer-circle');
			if(layer6) {
				map.removeLayer('dmdz-locate-layer-circle')
			}
		}
	}

	/**
	 * 添加定位
	 */
	locate = (gid, name) => {
		const {map, street, roadDataset, setSelectedFeature} = this.props;
		if(!map) return;
		const {namelistTab} = this.props;
		ajax_get({
			url: `/dm/list/${gid}/`,
			data: {type: namelistTab}
		}).then((res) => {
			if(!res) return;
			let result = res.data;
			if(!result || !result.length) {
				ToasterWarning({message: `未获取到${name}的信息`});
				return;
			}
			result  = result[0];
			// 加载属性面板
			setSelectedFeature && setSelectedFeature(result);
			if(!result.geom) {
				ToasterWarning({message: `未获取到${name}的定位信息，无法定位`});
				return;
			}
			try {
				let geom = JSON.parse(result.geom);
				if(geom.type === 'Point') {
					map.flyTo({
						center: geom.coordinates,
						zoom: 16
					});
				} else {
					const bbox = turf.bbox(geom);
					const bounds = new atlas.LngLatBounds([bbox[0], bbox[1]], [bbox[2], bbox[3]]);
					map.fitBounds(bounds,{
						padding: {top: 150, bottom:150, left: 200, right: 200}
					});
				}
				map.once("moveend", () => {
					let feature = map.queryRenderedFeatures(),
					feature_geo = null;
					feature.map(fea => {
						if(fea.properties.gid === result.gid) {
							feature_geo = fea.geometry;
						}
					})
					if(feature_geo) {
						geom = feature_geo;
					}
					let type = geom.type;
					this.removeLocate();
					if(type.indexOf("Line") >= 0) {
						const sourceId = 'atlasdata-ext-locateSource';
						const source = map.getSource(sourceId);
						if(!source) {
							map.addSource(sourceId, {
								type: 'geojson',
								data: {
									type: "FeatureCollection",
									features: [{
										type: 'Feature',
										geometry: geom,
										properties: result
									}]
								}
							});
						} else {
							source.setData({
								type: "FeatureCollection",
								features: [{
									type: 'Feature',
									geometry: geom,
									properties: result
								}]
							});
						}
						const layerId = 'dmdz-locate-layer';
						if(!map.getLayer(layerId)) {
							map.addLayer({
								id: 'dmdz-locate-layer',
								source: sourceId,
								'type': 'line',
								paint: {
									'line-color': '#08F',
									'line-opacity': 0.7,
									'line-width': 10
								},
								metadata: {
									name: "定位图层"
								}
							});
							let sign = flashLayer({
							    map: map,
							    layer: layerId,
							    type: 'paint',
							    property: 'line-color',
								on: '#08F',
								off: '#000',
							    interval: 200,
							    // timer: 3000,
							    end: () => {
							        map.setLayoutProperty(layerId, 'visibility', 'none');
							    }
							});
							updateState({sign})
						}
					}else if(type.indexOf("Point") >= 0) {
						const sourceId = 'atlasdata-ext-locateSource-point';
						const source = map.getSource(sourceId);
						if(!source) {
							map.addSource(sourceId, {
								type: 'geojson',
								data: {
									type: "FeatureCollection",
									features: [{
										type: 'Feature',
										geometry: geom,
										properties: result
									}]
								}
							});
						} else {
							source.setData({
								type: "FeatureCollection",
								features: [{
									type: 'Feature',
									geometry: geom,
									properties: result
								}]
							});
						}
						const layerId = 'dmdz-locate-layer-circle';
						if(!map.getLayer(layerId)) {
							map.addLayer({
								id: 'dmdz-locate-layer-circle',
								source: sourceId,
								'type': 'circle',
								paint: {
									'circle-color': '#08F',
									'circle-opacity': 0.7,
									'circle-radius': 10,
								},
								metadata: {
									name: "定位图层"
								}
							});
							let sign = flashLayer({
							    map: map,
							    layer: layerId,
							    type: 'paint',
							    property: 'circle-color',
								on: '#08F',
								off: '#000',
							    interval: 200,
							    // timer: 3000,
							    end: () => {
							        map.setLayoutProperty(layerId, 'visibility', 'none');
							    }
							});
							updateState({sign})
						}
					}
				});
			} catch {
			}
		});
	}


	/**
	 * 生成树节点
	 */
	getNode = ({name, isExpanded, nodeData, childNodes, icon, hasCaret}) => {
		const menu = (<Menu>
			<MenuItem onClick={(e) => this.position({name, type: nodeData.type})} icon="locate" text="定位" />
		</Menu>);
		return {
			id: name,
			label: name,
			hasCaret,
			isExpanded,
			icon: icon,
			nodeData: nodeData || {},
			secondaryLabel: (
				<Popover content={menu} position="right">
					<Icon icon="more" style={{cursor: 'pointer'}} />
				</Popover>
			),
			childNodes
		}
	}

	queryRoad(type) {
		const {street, districts} = this.props;
		if(!street || !districts || !type) return;
		let data = {type: type};
		if(districts) {
			data.districts = districts;
			if(districts === street) {
				data.districts = street;
			} else {
				data.streets = street;
			}
		}
		ajax_get({
			url: "/dm/list/",
			data,
		}).then((res)=>{
			this.setState({loaded: true});
			if(!res || !res.data) return;
			this.setState({nodes: res.data.map(d => d)});
		});
	}

    componentWillMount() {
		console.log(this.props.namelistTab)
		this.queryRoad(this.props.namelistTab);
    }

    render() {
		const {street,namelistTab} = this.props;
		if(!street) return null;
		const {nodes, filterKey, loaded} = this.state;
		let filterNodes = nodes || [];
		if(trim(filterKey)) {
			filterNodes = nodes.filter(node => {return node.indexOf(filterKey) >= 0;});
		}
		// 道路列表
		const listPanel = (
			<div className={styles.scrollWrapper}>
				<ScrollWrapper className={styles.scroll}>
					<div className={styles.nodeList}>
						<ul>
							{
								filterNodes.map((node, idx) => {
									const menu = (<Menu>
										<MenuItem onClick={() => {this.locate(node.gid)}} icon="locate" text="定位" />
										<MenuItem disabled={true} onClick={(e) => {}} icon="map" text="显示行政边界" />
									</Menu>);
									return (
										<li key={node + idx}>
											<div className="flex-vertical">
												<div onClick={() => {this.locate(node.gid)}} style={{width: "calc(100% - 60px)"}} ><Icon icon="map-marker" /> {node.name}</div>
												<div>
													<Popover content={menu} position="right">
														<Icon icon="more" style={{cursor: 'pointer'}} />
													</Popover>
												</div>
											</div>
										</li>
									)
								})
							}
						</ul>
						{
							filterNodes.length == 0 && loaded && <Blank desc="未查询到相关数据" />
						}
						{
							!loaded && <div style={{marginTop: 50}}><Spinner /></div>
						}
					</div>
				</ScrollWrapper>
			</div>
		);

        return (
			<div className={styles.main}>
				{/* <div>
					<h6 style={{padding: "0 10px 5px 10px",lineHeight: '30px'}}><Icon icon="key-option" style={{marginRight: "10px"}}></Icon>{street}</h6>
					<InputGroup
						className="bp3-right bp3-fill"
						leftIcon="filter"
						onChange={(e) => {this.setState({filterKey: e.target.value})}}
						placeholder="输入关键词过滤"
						value={filterKey}
					/>
				</div> */}
				<div>
					<Tabs id="LayerSettingTabs" vertical={true}
						selectedTabId={namelistTab}
						onChange={this.handleNavbarTabChange}
					>
						<Tab id="back" title={<Icon icon="circle-arrow-left" iconSize={20} color="#555" htmlTitle="返回图层列表" />} panel={null} />
						<Tab id="roads"
							title={<Icon icon="horizontal-distribution" color="#555"  iconSize={18} htmlTitle="道路街巷" />}
							panel={listPanel} />
						<Tab id="houses"
							// disabled= {true}
							title={<Icon icon="home" htmlTitle="居民点" color="#555"  iconSize={18} />} panel={listPanel} />
						<Tab id="buildings"
							// disabled= {true}
							title={<Icon iconSize={18} color="#555"  icon="office" htmlTitle="建筑物" />} panel={listPanel} />
            <Tab id="communities"
            	// disabled= {true}
            	title={<div className={styles.communities} title="群众自治组织" />} panel={listPanel} />
            <Tabs.Expander />
					</Tabs>
				</div>
			</div>
        )
    }
}

function mapStateToProps(state) {
    return {
		// countryGeometry: state.map.countryGeometry,
		map: state.map.map,
		countryDataset: state.map.countryDataset,
		streetDataset: state.map.streetDataset,
		roadDataset: state.map.roadDataset,
		sign: state.map.sign,
		namelistTab: state.map.namelistTab
    };
}

export default connect(mapStateToProps)(NameList);
